<template>
  <div class="tags">
    <!-- 面包屑导航区 -->
    <el-card class="breadcrumb-box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item
          ><a href="/#/manager/home">首页</a></el-breadcrumb-item
        >
        <el-breadcrumb-item>关卡管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>
    <!-- 卡片视图 -->
    <el-card class="level-list">
      <el-button
        size="large"
        type="primary"
        @click="addLevelDialogVisible = true"
        >新增关卡</el-button
      >
      <!-- 表格 -->
      <el-table
        :data="levelList"
        border
        stripe
        style="width: 100%;margin-top: 60px"
        v-loading="loading"
      >
        <el-table-column
          type="index"
          width="60"
          align="center"
          label="序号"
        ></el-table-column>
        <el-table-column prop="title" align="center" label="标题" width="160">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="large"
              @click="showLevelContentDialog('标题', scope.row.title)"
              style="width: 100%; justify-content: center;"
              >{{ scope.row.title.length > 10 ? scope.row.title.slice(0, 10)
                +
                '...' : scope.row.title.slice(0, 10) }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="tutorial"
          label="教程"
          align="center"
          width="160"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="large"
              @click="showLevelContentDialog('教程', scope.row.tutorial)"
              style="width: 100%; justify-content: center;"
              >{{ scope.row.tutorial.length > 10 ?
                scope.row.tutorial.slice(0, 10) + '...' : scope.row.tutorial.slice(0, 10) }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="example" align="center" label="示例" width="160">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="large"
              @click="showLevelContentDialog('示例', scope.row.example)"
              style="width: 100%; justify-content: center;"
              >{{ scope.row.example.length > 10 ?
                scope.row.example.slice(0, 10) + '...' : scope.row.example.slice(0, 10) }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="topic" label="题目" align="center" width="160">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="large"
              @click="showLevelContentDialog('题目', scope.row.topic)"
              style="width: 100%; justify-content: center;"
              >{{ scope.row.topic.length > 10 ? scope.row.topic.slice(0, 10)
                +
                '...' : scope.row.topic.slice(0, 10) }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="rate"
          label="评分/难度"
          align="center"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="typeName"
          label="类型"
          align="center"
          width="120"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.typeName === 'main'">主线关卡</el-tag>
            <el-tag v-else type="success">自定义关卡</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="levelCreateTime"
          label="创建时间"
          align="center"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200">
          <template #default="scope">
            <el-tooltip content="查看" placement="top" :enterable="false">
              <!-- 查看帖子按钮 -->
              <el-button
                type="success"
                :icon="View"
                @click="showLevelDialog(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <!-- 编辑帖子按钮 -->
              <el-button
                type="warning"
                :icon="Setting"
                @click="editLevelDialog(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                :icon="Delete"
                @click="deleteLevel(scope.row.id, scope.row.title)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 15, 20, 30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加关卡对话框 -->
    <el-dialog
      title="添加关卡"
      v-model="addLevelDialogVisible"
      @close="levelDialogClosed(addLevelFormRef)"
      width="60%"
      v-loading="loadingDialog"
      element-loading-text="Loading..."
      style="text-align: left;"
    >
      <!-- 添加关卡表单 -->
      <el-form
        :model="addLevelForm"
        :rules="addLevelFormRules"
        ref="addLevelFormRef"
        label-width="100px"
      >
        <el-form-item label="标题：" prop="title">
          <el-input
            placeholder="请输入标题"
            v-model="addLevelForm.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="教程：" prop="tutorial">
          <el-input
            v-model="addLevelForm.tutorial"
            :rows="8"
            type="textarea"
            placeholder="请输入教程"
          />
        </el-form-item>
        <el-form-item label="示例：" prop="example">
          <el-input
            v-model="addLevelForm.example"
            :rows="8"
            type="textarea"
            placeholder="请输入示例"
          />
        </el-form-item>
        <el-form-item label="题目：" prop="topic">
          <el-input
            v-model="addLevelForm.topic"
            :rows="4"
            type="textarea"
            placeholder="请输入题目"
          />
        </el-form-item>
        <el-form-item label="参考答案：" prop="rfanswer">
          <el-input
            placeholder="请输入参考答案"
            v-model="addLevelForm.rfanswer"
          ></el-input>
        </el-form-item>
        <el-form-item label="关卡类型：" prop="typeName">
          <el-select
            v-model="addLevelForm.typeName"
            placeholder="请选择关卡类型"
          >
            <el-option label="主线关卡" value="main" />
            <el-option label="自定义关卡" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="评分/难度：" prop="rate">
          <el-input-number
            v-model="addLevelForm.rate"
            :precision="1"
            :step="0.1"
            :max="5"
            :min="0.1"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="footer">
        <el-button @click="addLevelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addLevel(addLevelFormRef)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 查看关卡对话框 -->
    <el-dialog
      title="查看关卡"
      v-model="showLevelDialogVisible"
      @close="showLevelContent = ''"
      width="60%"
      style="text-align: left;"
    >
      <el-card class="level-content">
        <md-viewer :value="showLevelContent" />
      </el-card>
      <span slot="footer" class="footer">
        <el-button type="primary" @click="showLevelDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 查看关卡内容对话框 -->
    <el-dialog
      :title="levelContentName"
      v-model="showLevelContentDialogVisible"
      @close="levelContent = ''"
      width="60%"
      style="text-align: left"
    >
      <el-card class="level-content">
        <md-viewer :value="levelContent" />
      </el-card>
      <span slot="footer" class="footer">
        <el-button type="primary" @click="showLevelContentDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 编辑关卡对话框 -->
    <el-dialog
      title="编辑关卡"
      v-model="editLevelDialogVisible"
      @close="levelDialogClosed(editLevelFormRef)"
      width="70%"
      v-loading="loadingDialog"
      element-loading-text="Loading..."
      style="text-align: left;"
    >
      <!-- 编辑关卡表单 -->
      <el-form
        :model="editLevelForm"
        :rules="editLevelFormRules"
        ref="editLevelFormRef"
        label-width="100px"
      >
        <el-form-item label="标题：" prop="title">
          <div style="width: 100%">
            <el-input
              v-if="!editTitle"
              disabled
              v-model="editLevelForm.title"
              style="width: 85%"
            ></el-input>
            <el-input
              v-else
              placeholder="请输入标题"
              v-model="editLevelForm.title"
              style="width: 85%"
            ></el-input>
            <el-button
              :type="editTitle ? 'success' : 'warning'"
              @click="editTitle = !editTitle"
              style="float: right; margin-top: 2px"
              >{{ editTitle ? '确定' : '编辑' }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="教程：" prop="tutorial">
          <div style="width: 100%">
            <el-card
              style="width: 85%; float: left;height: 300px;overflow: auto;"
              v-if="!editTutorial"
            >
              <md-viewer :value="editLevelForm.tutorial" />
            </el-card>
            <el-input
              v-else
              v-model="editLevelForm.tutorial"
              :rows="8"
              type="textarea"
              placeholder="请输入教程"
              style="width: 85%"
            />
            <el-button
              :type="editTutorial ? 'success' : 'warning'"
              @click="editTutorial = !editTutorial"
              style="float: right; margin-top: 2px"
              >{{ editTutorial ? '确定' : '编辑' }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="示例：" prop="example">
          <div style="width: 100%">
            <el-card
              style="width: 85%; float: left;height: 300px;overflow: auto;"
              v-if="!editExample"
            >
              <md-viewer :value="editLevelForm.example" />
            </el-card>
            <el-input
              v-else
              v-model="editLevelForm.example"
              :rows="8"
              type="textarea"
              placeholder="请输入示例"
              style="width: 85%"
            />
            <el-button
              :type="editExample ? 'success' : 'warning'"
              @click="editExample = !editExample"
              style="float: right; margin-top: 2px"
              >{{ editExample ? '确定' : '编辑' }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="题目：" prop="topic">
          <div style="width: 100%">
            <el-card style="width: 85%; float: left;" v-if="!editTopic">
              <md-viewer :value="editLevelForm.topic" />
            </el-card>
            <el-input
              v-else
              v-model="editLevelForm.topic"
              :rows="4"
              type="textarea"
              placeholder="请输入题目"
              style="width: 85%"
            />
            <el-button
              :type="editTopic ? 'success' : 'warning'"
              @click="editTopic = !editTopic"
              style="float: right; margin-top: 2px"
              >{{ editTopic ? '确定' : '编辑' }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="参考答案：" prop="rfanswer">
          <div style="width: 100%">
            <el-input
              v-if="!editRfanswer"
              disabled
              v-model="editLevelForm.rfanswer"
              style="width: 85%"
            ></el-input>
            <el-input
              v-else
              placeholder="请输入标题"
              v-model="editLevelForm.rfanswer"
              style="width: 85%"
            ></el-input>
            <el-button
              :type="editRfanswer ? 'success' : 'warning'"
              @click="editRfanswer = !editRfanswer"
              style="float: right; margin-top: 2px"
              >{{ editRfanswer ? '确定' : '编辑' }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="关卡类型：" prop="typeName">
          <el-select
            v-model="editLevelForm.typeName"
            placeholder="请选择关卡类型"
          >
            <el-option label="主线关卡" value="main" />
            <el-option label="自定义关卡" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="评分/难度：" prop="rate">
          <el-input-number
            v-model="editLevelForm.rate"
            :precision="1"
            :step="0.1"
            :max="5"
            :min="0.1"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="footer">
        <el-button @click="editLevelDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editLevel(editLevelFormRef)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { FormRules, FormInstance, ElMessage, ElMessageBox } from 'element-plus';
import { Delete, View, Setting } from '@element-plus/icons-vue'
import { ref, getCurrentInstance, ComponentInternalInstance, onMounted, reactive } from 'vue';
import MdViewer from '@/components/MdViewer.vue';

const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 关卡列表
interface levelList {
  id: Number
  title: String
  tutorial: String
  example: String
  topic: String
  rfanswer: String,
  levelCreateTime: Date
  typeName: String,
  rate: Number
};
const levelList = ref<levelList[]>([]);
// 加载
const loading = ref(false);
const loadingDialog = ref(false);
// 控制对话框的显示与隐藏
const addLevelDialogVisible = ref(false);
const showLevelDialogVisible = ref(false);
const showLevelContentDialogVisible = ref(false);
const editLevelDialogVisible = ref(false);
// 获取关卡列表的页码参数对象
const queryInfo = reactive({
  // 当前的页数
  pageNum: 1,
  // 当前每页显示的数据条数
  pageSize: 10,
});
// 关卡列表总条数
const total = ref(0);
// 添加关卡的表单数据对象
let addLevelForm = reactive({
  id: null,
  title: '',
  tutorial: '',
  example: '',
  topic: '',
  rfanswer: '',
  typeName: '',
  rate: null
});
const addLevelFormRef = ref();
// 添加关卡表单验证规则
const addLevelFormRules = reactive<FormRules>({
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['blur', 'change'],
    },
  ],
  tutorial: [
    {
      required: true,
      message: '请输入教程',
      trigger: ['blur', 'change'],
    },
  ],
  example: [
    {
      required: true,
      message: '请输入示例',
      trigger: ['blur', 'change'],
    },
  ],
  topic: [
    {
      required: true,
      message: '请输入题目',
      trigger: ['blur', 'change'],
    },
  ],
  rfanswer: [
    {
      required: true,
      message: '请输入参考答案',
      trigger: ['blur', 'change'],
    },
  ],
  typeName: [
    {
      required: true,
      message: '请选择关卡类型',
      trigger: ['blur', 'change'],
    },
  ],
  rate: [
    {
      required: true,
      message: '请输入难度系数',
      trigger: ['blur', 'change'],
    },
  ],
});
// 添加关卡的表单数据对象
let editLevelForm = reactive({
  id: null,
  title: '',
  tutorial: '',
  example: '',
  topic: '',
  rfanswer: '',
  typeName: '',
  rate: null
});
const editLevelFormRef = ref();
// 添加关卡表单验证规则
const editLevelFormRules = reactive<FormRules>({
  title: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['blur', 'change'],
    },
  ],
  tutorial: [
    {
      required: true,
      message: '请输入教程',
      trigger: ['blur', 'change'],
    },
  ],
  example: [
    {
      required: true,
      message: '请输入示例',
      trigger: ['blur', 'change'],
    },
  ],
  topic: [
    {
      required: true,
      message: '请输入题目',
      trigger: ['blur', 'change'],
    },
  ],
  rfanswer: [
    {
      required: true,
      message: '请输入参考答案',
      trigger: ['blur', 'change'],
    },
  ],
  typeName: [
    {
      required: true,
      message: '请选择关卡类型',
      trigger: ['blur', 'change'],
    },
  ],
  rate: [
    {
      required: true,
      message: '请输入难度系数',
      trigger: ['blur', 'change'],
    },
  ],
});
// 查看关卡
const showLevelContent = ref();
// 展示关卡内容
const levelContent = ref();
const levelContentName = ref();
// 编辑关卡信息
const editTitle = ref(false);
const editTutorial = ref(false);
const editExample = ref(false);
const editTopic = ref(false);
const editRfanswer = ref(false);

onMounted(() => {
  getLevelList();
})

// 获取所有关卡
function getLevelList() {
  loading.value = true;
  proxy.$request.level.getAllLevel(queryInfo).then((res: any) => {
    levelList.value = [];
    levelList.value = res.data.list;
    total.value = res.data.total;
    loading.value = false;
  });
};
// 监听 pagesize 改变
function handleSizeChange(newSize: any) {
  queryInfo.pageSize = newSize;
  getLevelList();
};
// 监听页码值改变
function handleCurrentChange(newNum: any) {
  queryInfo.pageNum = newNum;
  getLevelList();
};
// 监听添加/编辑关卡对话框的关闭事件
function levelDialogClosed(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.resetFields();
}
// 添加关卡
function addLevel(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) return;
    loadingDialog.value = true;
    proxy.$request.level.addNewLevel(addLevelForm).then(() => {
      ElMessage({
        message: '添加成功',
        type: 'success',
        duration: 1000,
      });
      getLevelList();
      formEl.resetFields();
      loadingDialog.value = false;
      addLevelDialogVisible.value = false;
    });
  });
};
// 展示关卡
function showLevelDialog(row: any) {
  showLevelDialogVisible.value = true;
  console.log('row===>', row);
  showLevelContent.value = '# ' + row.title
    + '\n## 教程\n' + row.tutorial
    + '\n## 示例\n' + row.example
    + '\n## 题目\n' + row.topic;
}
// 展示关卡内容
function showLevelContentDialog(name: String, content: String) {
  levelContentName.value = name;
  levelContent.value = content;
  showLevelContentDialogVisible.value = true;
}
// 编辑关卡内容
function editLevelDialog(row: any) {
  editLevelDialogVisible.value = true;
  editLevelForm.id = row.id;
  editLevelForm.title = row.title;
  editLevelForm.tutorial = row.tutorial;
  editLevelForm.example = row.example;
  editLevelForm.topic = row.topic;
  editLevelForm.rfanswer = row.rfanswer;
  editLevelForm.typeName = row.typeName;
  editLevelForm.rate = row.rate;
}
// 编辑关卡
function editLevel(formEl: FormInstance | undefined) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) return;
    loadingDialog.value = true;
    proxy.$request.level.addNewLevel(editLevelForm).then(() => {
      ElMessage({
        message: '编辑成功',
        type: 'success',
        duration: 1000,
      });
      getLevelList();
      levelDialogClosed(formEl);
      loadingDialog.value = false;
      editLevelDialogVisible.value = false;
    });
  });
};
// 删除关卡
function deleteLevel(id: Number, title: String) {
  ElMessageBox.confirm(
    '此操作将删除 <strong>' + title + '</strong> 关卡, 是否继续?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
    }
  )
    .then(() => {
      loading.value = true;
      proxy.$request.level
        .deleteLevel({ id: id })
        .then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功',
            duration: 1000,
          });
          getLevelList();
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
        duration: 1000,
      });
    });
};
</script>

<style lang="less" scoped>
.breadcrumb-box {
  position: fixed;
  top: 60px;
  height: 36px;
  width: 100%;
  border-radius: 0;
  padding: 0 20px;
  border: 0;
  margin: 0 0 20px !important;
  z-index: 9;

  .el-breadcrumb {
    line-height: 36px;
  }

  /deep/ .el-card__body {
    padding: 0;
  }
}

.level-list {
  margin: 60px 20px 0;

  .el-button {
    float: left;
  }

  .el-pagination {
    margin-top: 20px;
    justify-content: center;
  }
}

.footer {
  display: flex;
  justify-content: end;
  width: 100%;
  margin-top: 20px;
}

.level-content {
  text-align: center;
  margin: 0 20px 40px;
}

/deep/ .el-dialog__title {
  font-weight: 600;
  font-size: 22px;
}
</style>
